import {createServer} from 'http'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import {StaticRouter} from 'react-router'
import App from './App'
import express from 'express'
import path from 'path';

let app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/age', function (req, resp) {
    resp.send(`{'age': 1991}`);
    resp.end();
})

app.get('/number/:number', function (req, res) {
    var sid = getCookieNumber(req, res, true);
    var newNumber = req.params.number;
    console.log('syncNumber ' + sid + " = " + newNumber);
    cookieManager[sid] = newNumber;
    res.send(`{"msg":"ok"}`);
    res.end();
});

app.get('*', dealRequest);

function dealRequest(req, res) {
    const context = {}
    var number = getCookieNumber(req, res);
    console.log('number = ' + number);
    const html = ReactDOMServer.renderToString(
        <StaticRouter
            location={req.url}
            context={context}
        >
            <App number={number}/>
        </StaticRouter>
    );
    var script_ = 'var NUMBER = ' + number;

    var html_ = ReactDOMServer.renderToStaticMarkup(
        <html>
        <head>
            <link rel="stylesheet" href={`${__dirname}/style.css`}></link>
        </head>
        <body>
        <div id="app" dangerouslySetInnerHTML={{__html: html}}/>
        <script dangerouslySetInnerHTML={{__html: script_}}></script>
        <script src={`${__dirname}/main.js`}></script>
        </body>
        </html>
    );

    if (context.url) {
        console.log('redirect -> ' + context.url);
        res.writeHead(301, {
            Location: context.url
        })
        res.end()
    } else {
        res.write(html_);
        res.end()
    }
}

const cookieManager = {};

function getCookieNumber(req, res, justSid) {
    var ck = req.headers.cookie;
    if (ck) {
        var cks = ck.split(';');
        var sid = 0;
        for (var i = 0; i < cks.length; i++) {
            var pairs = cks[i].split('=');
            if (pairs[0].trim() == 'sid') {
                sid = pairs[1];
            }
        }
    }
    if (justSid) {
        return sid;
    }
    if (sid) {
        if (cookieManager[sid]) {
            console.log('sid = ' + sid);
            return cookieManager[sid];
        }
    } else {
        sid = generateSid();
    }
    console.log('sid = ' + sid);
    cookieManager[sid] = 10000;
    res.cookie('sid', sid);
    return 10000;
}

function generateSid() {
    var tmpId = parseInt(Math.random() * 100000);
    if (cookieManager[tmpId]) {
        return generateSid();
    }
    return tmpId;
}

app.listen(3000);
